package xyz.xuminghai.javafx_learn.stage;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundImage;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Stage;

import java.io.File;

/**
 * 2023/1/9 14:18 星期一<br/>
 * <p>
 * 文件选择器窗口
 *
 * @author xuMingHai
 */
public class FileChooserApp extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择图片");
        // 文件选择过滤器
        fileChooser.getExtensionFilters().add(
                new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif")
        );

        Button button = new Button("打开图片");
        button.setOnAction(event -> {
            File file = fileChooser.showOpenDialog(primaryStage);
            System.out.println("file = " + file);
            if (file != null) {
                // 选择了图片，设置为按钮背景
                BackgroundImage backgroundImage = new BackgroundImage(
                        new Image(file.toURI().toString()),
                        null, null, null, null
                );
                button.setBackground(new Background(backgroundImage));
            }
        });

        primaryStage.setTitle("FileChooserApp");
        primaryStage.setScene(new Scene(button));
        primaryStage.show();
    }

}
